<template>
  <div class="group-container">
    <el-card shadow="never">
      <!---搜索框---->
      <div class="group-header">
        <el-form :inline="true" :model="queryParams">
          <el-form-item>
            <span class="title-label">工作组名称</span>
            <el-input
                v-model="queryParams.group_name"
                placeholder="请输入工作组名称"
                style="width: 300px"
                clearable
            ></el-input>
          </el-form-item>

          <el-form-item>
            <span class="title-label">状态</span>
            <el-select
                v-model="queryParams.status"
                placeholder="菜单状态"
                style="width: 220px"
            >
              <el-option label="正常" :value="0"></el-option>
              <el-option label="停用" :value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item style="margin-left: 25px">
            <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
            >搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
              重置
            </el-button>
          </el-form-item>
          <div class="button-container">
            <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAddGroup"
            >
              新增
            </el-button>
          </div>
        </el-form>
      </div>

      <!-----表格------>
      <div class="group-body">
        <el-table
            ref="table"
            :data="groupList"
            :border="false"
            style="width: 100%"
            :header-cell-style="{ background: '#f8f8f9', color: '#606266' }"
            :default-sort="{ prop: 'status', order: 'ascending' }"
        >
          <el-table-column type="expand">
            <template slot-scope="props">
              <!-----表格居中------>
              <div
                  style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                "
              >
                <el-table
                    :data="getGroupMembersByGroupId(props.row.groupId)"
                    style="width: 100%; border: 1px solid #ebeef5"
                    :border="true"
                    :header-cell-style="{
                    background: '#F2F6FC',
                    color: '#606266',
                  }"
                >
                  <el-table-column
                      fixed
                      label="组员序号"
                      align="center"
                      style="width: 20%"
                  >
                    <template scope="scope">
                      <span>{{ scope.$index + 1 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                      prop="nickName"
                      label="昵称"
                      align="center"
                  ></el-table-column>
                  <el-table-column
                      prop="roleNameZh"
                      label="角色名称"
                      align="center"
                  >
                    <template slot-scope="scope">
                      <el-tag type="info">{{ scope.row.roleNameZh }}</el-tag>
                    </template></el-table-column
                  >
                </el-table>
              </div>
            </template>
          </el-table-column>

          <el-table-column
              label="序号"
              prop="groupId"
              width="60"
              align="center"
          ></el-table-column>
          <el-table-column label="名称" prop="groupName" align="center" />
          <el-table-column label="组长" prop="nickName" align="center" />
          <el-table-column label="创建时间" prop="startDate" align="center" />
          <el-table-column label="截止时间" prop="dueDate" align="center" />
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
              <el-tag v-if="!scope.row.status" type="success">正常</el-tag>
              <el-tag v-else type="danger">停用</el-tag>
            </template>
          </el-table-column>
          <!----更多操作---->
          <el-table-column label="操作" align="center" width="190">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleAddEmployee(scope.row)"
                  v-if="showAddEmployee(scope.row)"
              >
                添加组员
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-chicken"
                  @click="handleCheck(scope.row)"
                  v-if="!scope.row.status"
              >
                查看任务
              </el-button>
              <!--              <el-button-->
              <!--                  size="mini"-->
              <!--                  type="text"-->
              <!--                  icon="el-icon-delete"-->
              <!--                  @click="handleDelete(scope.row)"-->
              <!--                  v-if="!scope.row.status"-->
              <!--              >-->
              <!--                删除-->
              <!--              </el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-----分页------>
      <div class="user-footer">
        <el-pagination
            :page-sizes="[5, 10, 20, 50, 100]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加 工作组 对话框  -->
    <el-dialog
        :title="dialogTitle"
        width="700px"
        :visible="dialogGroupShow"
        :before-close="handleGroupClose"
    >
      <el-form orm :model="groupInfo" ref="userInfoForm">
        <!--  输入工作组名称  -->
        <el-form-item label="名称" label-width="80px">
          <el-input
              placeholder="请输入工作组名称"
              v-model="group.groupName"
              style="width: 300px"
          ></el-input>
        </el-form-item>
        <!--  输入时间  -->
        <el-form-item label="开始时间" label-width="80px">
          <el-col :span="8">
            <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="startDate.date1"
                style="width: 100%"
            ></el-date-picker>
          </el-col>
          <el-col class="line" style="text-align: center" :span="1">-</el-col>
          <el-col :span="8">
            <el-time-picker
                placeholder="选择时间"
                v-model="startDate.date2"
                style="width: 100%"
            ></el-time-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="结束时间" label-width="80px">
          <el-col :span="8">
            <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="dueDate.date1"
                style="width: 100%"
            ></el-date-picker>
          </el-col>
          <el-col class="line" style="text-align: center" :span="1">-</el-col>
          <el-col :span="8">
            <el-time-picker
                placeholder="选择时间"
                v-model="dueDate.date2"
                style="width: 100%"
            ></el-time-picker>
          </el-col>
        </el-form-item>
        <!--选择组长---->
        <el-form-item label="组长" label-width="80px">
          <el-select
              v-model="selectedEmployee"
              filterable
              placeholder="请搜索"
              style="width: 192px"
          >
            <el-option
                v-for="item in employeeList"
                :key="item.id"
                :label="item.nickName"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGroupForm">确定</el-button>
        <el-button @click="handleGroupClose">取消</el-button>
      </span>
    </el-dialog>

    <!--  添加组员  -->
    <el-dialog
        :title="dialogTitle"
        width="1000px"
        :visible="dialogUserShow"
        :before-close="handleUserClose"
    >
      <el-transfer
          filterable
          filter-placeholder="请输入组员姓名"
          :titles="['选择组员', '工作组成员']"
          :button-texts="['移除', '添加']"
          v-model="choosedEmployee"
          :props="{
          key: 'userId',
          label: 'nickName',
        }"
          :data="waitForChooseEmployee"
          style="display: flex; justify-content: center; align-items: center"
          @change="handleChange"
      >
      </el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUserForm()">确定</el-button>
        <el-button @click="handleUserClose">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllGroup,
  findEmployeeByGroupId,
  addEmployeeToGroup,
  addGroup,
  findEmployee,
  deleteGroup,
  findGroupByUserId,
} from "@/api/group";
import { getCurrentUserInfo } from "@/api/user";

export default {
  name: "ReceiveTask",
  data() {
    return {
      // 查询参数
      queryParams: {
        // 菜单名称
        group_name: "",
        // 菜单状态
        status: "",
      },

      //工作组总数
      total: 0,
      // 当前页数
      curPage: 1,
      // 页面大小
      size: 10,

      user_id: "",

      groupNumber: "",
      leaderNumber: "",

      // 对话框标题
      dialogTitle: "",
      // 添加工作组是否显示
      dialogGroupShow: false,
      // 添加组员是否显示
      dialogUserShow: false,

      // 工作组列表
      groupList: [],
      groupIdList: [],

      groupMenberInfoList: [
        {
          groupId: "",
          groupMenberInfo: [],
        },
      ],

      // 工作组对象
      group: {},
      // 时间对象
      startDate: { date1: "", date2: "" },
      dueDate: { date1: "", date2: "" },
      // 工作组更新对象
      groupInfo: {
        groupName: "",
        groupLeaderId: "",
        startDate: "",
        dueDate: "",
      },

      waitForChooseEmployee: [],
      choosedEmployee: [],

      // 员工列表
      employeeList: [],
      // 员工对象
      employee: {},
      // 选择组长
      selectedEmployee: null,

      // 表格数据是否重新渲染
      refreshTable: true,

      groupDTOForSearch: {
        dueDate: "",
        groupId: -1,
        groupLeaderId: -1,
        groupName: "",
        startTime: "",
        status: -1,
      },
    };
  },

  mounted() {
    this.getTableData();
    this.getUserData();
  },

  methods: {
    //查看任务，跳转到其他页面
    handleCheck(row) {
      // 在这里你可以使用编程式导航代替直接点击router-link
      this.$router.push({ path: "/test", query: { param1: row } });
    },
    // 获取工作组数据
    getTableData() {
      findGroupByUserId().then((result) => {
        this.groupList = result;
        let groups = this.groupList;
        this.total = groups.size;
        this.getGroupIdList();
        this.getGroupMembers();
      });
      getCurrentUserInfo().then((result) => {
        this.user_id = result.id;
      });
    },

    // 获取用户数据
    getUserData() {
      findEmployee().then((result) => {
        this.employeeList = result;
      });
    },

    // 保存groupId到groupIdList
    getGroupIdList() {
      for (let i = 0; i < this.groupList.length; i++) {
        // 当groupIdList不含groupId时加入
        if (!this.groupIdList.includes(this.groupList[i].groupId)) {
          this.groupIdList.push(this.groupList[i].groupId);
        }
      }
    },

    // 获取所有工作组人员信息
    getGroupMembers() {
      for (let i = 0; i < this.groupIdList.length; i++) {
        findEmployeeByGroupId({
          group_id: this.groupIdList[i],
        }).then((result) => {
          // 保存数据
          const temp = {
            groupId: this.groupIdList[i],
            groupMenberInfo: result,
          };
          this.groupMenberInfoList.push(temp);
        });
      }
      this.groupMenberInfoList.shift();
    },

    // 根据groupId找到对应的组成员信息
    getGroupMembersByGroupId(groupId) {
      const groupInfo = this.groupMenberInfoList.find(
          (group) => group.groupId === groupId
      );
      return groupInfo ? groupInfo.groupMenberInfo : [];
    },

    // 点击新增工作组
    handleAddGroup() {
      this.dialogTitle = "添加工作组";
      this.dialogGroupShow = true;
    },

    // 新建工作组
    submitGroupForm() {
      this.groupInfo.groupName = this.group.groupName;
      this.groupInfo.groupLeaderId = this.selectedEmployee;
      this.groupInfo.startDate = this.startDate.date1;
      this.groupInfo.dueDate = this.dueDate.date1;
      // 发送请求
      addGroup(this.groupInfo).then(() => {
        this.getTableData();
      });
      this.handleGroupClose();
    },

    // 点击添加组员
    handleAddEmployee(row) {
      this.dialogTitle = "添加组员";
      findEmployeeByGroupId({
        group_id: row.groupId,
      }).then((result) => {
        for (let i = 0; i < result.length; i++) {
          this.choosedEmployee.push(result[i].id);
        }
      }),
          (this.groupNumber = row.groupId);
      this.leaderNumber = row.groupLeaderId;
      this.waitForChooseEmployee = [];
      for (let i = 0; i < this.employeeList.length; i++) {
        if (this.employeeList[i].id === row.groupLeaderId) {
          this.waitForChooseEmployee.push({
            userId: this.employeeList[i].id,
            nickName: this.employeeList[i].nickName,
            disabled: true,
          });
        } else {
          this.waitForChooseEmployee.push({
            userId: this.employeeList[i].id,
            nickName: this.employeeList[i].nickName,
            disabled: false,
          });
        }
      }

      this.dialogUserShow = true;
    },

    handleChange() {},

    // 发送添加组员请求
    // submitUserForm() {
    //   for (let i = 0; i < this.choosedEmployee.length; i++) {
    //     if (this.choosedEmployee[i] !== this.leaderNumber) {
    //       addEmployeeToGroup({
    //         group_id: this.groupNumber,
    //         user_id: this.choosedEmployee[i],
    //       }).then((result) => {

    //       });
    //     }
    //   }
    //         this.getTableData();
    //         this.handleUserClose();
    // },

    submitUserForm() {
      const promises = []; // 用于存储所有的 Promise

      for (let i = 0; i < this.choosedEmployee.length; i++) {
        if (this.choosedEmployee[i] !== this.leaderNumber) {
          // 将每个 addEmployeeToGroup 请求的 Promise 存储起来
          promises.push(
              addEmployeeToGroup({
                group_id: this.groupNumber,
                user_id: this.choosedEmployee[i],
              })
          );
        }
      }
      location.reload();
    },

    // 删除工作组
    handleDelete(row) {
      this.$confirm("确定删除 " + row.groupName + " 吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            // 执行删除操作
            deleteGroup({ group_id_list: row.groupId }).then(() => {
              // 重新获取表格数据
              this.getTableData();
            });
          })
          .catch(() => {});
    },

    showAddEmployee(row) {
      if (!row.status && row.groupLeaderId === this.user_id)
        return true;
      else return false;
    },

    // 关闭对话框
    handleGroupClose() {
      this.dialogGroupShow = false;
      this.reset();
    },
    handleUserClose() {
      this.dialogUserShow = false;
      this.reset();
    },

    // 刷新表单数据
    reset() {
      // 修改表单标题
      this.dialogTitle = "";
      // 重置表单对象
      this.group = {};
      this.startDate = {};
      this.dueDate = {};
      this.selectedEmployee = [];
      this.choosedEmployee = [];
      this.waitForChooseEmployee = [];
      this.groupNumber = "";
      this.leaderNumber = "";
      // 重置用户信息对象
      this.groupInfo = {
        groupName: "",
        groupLeaderId: "",
        startDate: "",
        dueDate: "",
      };
    },

    // 当页面大小发生变化时
    handleSizeChange(val) {
      this.size = val;
      // 重新获取数据
      this.getTableData();
    },

    // 点击了重置按钮
    resetQuery() {
      // 重新设置查询参数
      this.queryParams.group_name = "";
      // 菜单状态
      this.queryParams.status = "";

      this.getTableData();
    },

    // 当前页发生变化时
    handleCurrentChange(val) {
      this.curPage = val;
      // 重新获取数据
      this.getTableData();
    },

    // 条件搜索
    handleQuery() {
      this.getGroupsByParams();
    },
    getGroupsByParams() {
      getAllGroup(
          {
            curPage: this.curPage,
            size: this.size,
          },
          {
            groupName: this.queryParams.group_name,
            status: this.queryParams.status,
          }
      ).then((result) => {
        this.groupList = result.list;
        this.total = result.total;
      });
    },

  },
};
</script>

<style lang="scss" scoped>
.group-container {
  margin-top: 10px;

  .group-header {
    margin-top: 10px;
    padding-left: 15px;

    .title-label {
      font-size: 14px;
      font-weight: 700;
      color: #606266;
      margin-right: 12px;
    }
  }

  .group-body {
    margin: 20px 15px 30px 15px;
  }

  .user-footer {
    padding-left: 15px;
    margin-top: 40px;
  }
}
</style>